import axios from 'axios'
import { Toast } from 'mint-ui';
const Message = {
    error: function(msg){
        console.error(msg)
    }
}

axios.defaults.baseURL = '/wxbk/'
// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
    // 对响应数据做些事
    if (!res.status === 200) {
        return Promise.reject(res)
    }
    return res
}, (error) => {
    if (error.message && error.message.indexOf('timeout') > -1) {
       Toast('请求超时，请刷新页面重试')
    }
    let status = error.response.status
    switch (status) {
        case 400:
           Toast('对不起，请求的参数错误，请确认后重试')
            break
        case 401:
            if(process.env.NODE_ENV === 'production'){
                window.location.href = 'visitor.html#/invalid'
            }
            break
        case 403:
           Toast('对不起，你没有权限进行此项操作')
            break
        case 404:
           Toast('对不起，你请求的服务不存在')
            break
        case 422:
           Toast('您提交的数据格式不正确，请重新检查')
            break
        case 500:
           Toast('服务器内部可能正在升级,请稍后再试')
            break
        default:
           Toast('对不起，系统繁忙，请稍后再试，错误代码(' + status + ')')
    }
    return Promise.reject(error)
})


export function _post(url, pms, ops) {
    return new Promise((resolve, reject) => {
        axios.post(url, pms, ops).then(response => {
            if (response.data.code == 0) {
                resolve(response)
            } else {
               Toast(response.data.msg || '系统繁忙')
                reject(response)
            }
        }).catch((error) => {
            reject(error)
        })
    })
}

export function _get(url, pms) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: pms
        }).then(response => {
            if (response.data.code === 0) {
                resolve(response)
            } else {
               Toast(response.data.msg || '系统繁忙')
                reject(response)
            }
        }).catch((error) => {
            reject(error)
        })
    })
}

export function _delete(url, pms) {
    return new Promise((resolve, reject) => {
        axios.delete(url, { data: pms }).then(response => {
            if (response.data.code === 0) {
                resolve(response)
            } else {
               Toast(response.data.msg || '系统繁忙')
                reject(response)
            }
        }).catch((error) => {
            reject(error)
        })
    })
}

export function _upload(url, data) {
    return new Promise((resolve, reject) => {
        axios.post( url, data, {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(response => {
            // if (response.data.code === 0) {
                resolve(response)
            // } else {
            //    Toast(response.data.msg || '系统繁忙')
            //     reject(response)
            // }
        }).catch((error) => {
            reject(error)
        })
    })
}